package com.lastproject.ejb.dao;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import com.lastproject.dto.ReviewDTO;
import com.lastproject.ejb.entities.Review;
import com.lastproject.ejb.util.ReviewConversion;

/**
 * Session Bean implementation class ReviewDAO author : Dan Gandila
 */
@Stateless
public class ReviewDAO implements ReviewDAORemote {

	@PersistenceContext(unitName = "LastProjectEJB")
	private EntityManager em;
	@EJB
	ReviewConversion conv;

	public ReviewDAO() {
	}

	@Override
	public void create(ReviewDTO entity) {
		em.persist(conv.fromDTO(entity));
	}

	@Override
	public void edit(ReviewDTO entity) {
		em.merge(conv.fromDTO(entity));
	}

	@Override
	public void remove(ReviewDTO entity) {
		Review r = em.find(Review.class, entity.getId());
		em.remove(em.merge(r));
	}

	@Override
	public ReviewDTO findByID(Object id) {
		Review r = em.find(Review.class, id);
		ReviewDTO review = conv.fromEntity(r);
		return review;
	}

	@Override
	public List<ReviewDTO> findAll() {
		List<Review> reviews = em.createNamedQuery("Review.findAll",
				Review.class).getResultList();
		List<ReviewDTO> reviewsDto = new ArrayList<ReviewDTO>();

		for (Review r : reviews) {
			ReviewDTO rDto = new ReviewDTO();
			rDto = conv.fromEntity(r);
			reviewsDto.add(rDto);
		}
		return reviewsDto;
	}

	/**
	 * returneaza lista review-urilor unei carti
	 */
	@Override
	public List<ReviewDTO> getReviewsByBookId(int bookId) {

		List<Review> reviews = em
				.createQuery("SELECT r FROM Review r where r.book.id = :id",
						Review.class).setParameter("id", bookId)
				.getResultList();

		List<ReviewDTO> reviewsDto = new ArrayList<ReviewDTO>();

		for (Review r : reviews) {
			ReviewDTO rDto = new ReviewDTO();
			rDto = conv.fromEntity(r);
			reviewsDto.add(rDto);
		}
//		System.out.println("reviewDAO:getreviewsByBookId " + reviewsDto.size());
		return reviewsDto;
	}
}
